﻿using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls;

namespace SmartPart
{
    [Guid("461e7a14-b966-422a-95e8-3a17d5a39aed")]
    public class AJAXSmartPart : SmartPart
    {
        private ScriptManager _AjaxManager;

        /// <summary>
        /// Exposes the Page's script manager. The value is not set until after OnInit
        /// </summary>
        [WebPartStorage(Storage.None)]
        public ScriptManager AjaxManager
        {
            get { return _AjaxManager; }
            set { _AjaxManager = value; }
        }

        /// <summary>
        /// Oninit fires before page load. Modifications to the page that are necessary to support Ajax are done here.
        /// </summary>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            //get the existing ScriptManager if it exists on the page
            _AjaxManager = ScriptManager.GetCurrent(this.Page);

            if (_AjaxManager == null)
            {
                //create new ScriptManager and EnablePartialRendering
                _AjaxManager = new ScriptManager();
                _AjaxManager.EnablePartialRendering = true;
                _AjaxManager.EnableScriptLocalization = true;

                // Fix problem with postbacks and form actions (DevDiv 55525)
                Page.ClientScript.RegisterStartupScript(typeof(AJAXSmartPart), this.ID, "_spOriginalFormAction = document.forms[0].action;", true);

                //tag:"form" att:"onsubmit" val:"return _spFormOnSubmitWrapper()" blocks async postbacks after the first one
                //not calling "_spFormOnSubmitWrapper()" breaks all postbacks
                //returning true all the time, somewhat defeats the purpose of the _spFormOnSubmitWrapper() which is to block repetitive postbacks, but it allows MS AJAX Extensions to work properly
                //its a hack that hopefully has minimal effect
                if (this.Page.Form != null)
                {
                    string formOnSubmitAtt = this.Page.Form.Attributes["onsubmit"];
                    if (!string.IsNullOrEmpty(formOnSubmitAtt) && formOnSubmitAtt == "return _spFormOnSubmitWrapper();")
                    {
                        this.Page.Form.Attributes["onsubmit"] = "_spFormOnSubmitWrapper();";
                    }

                    //add the ScriptManager as the first control in the Page.Form
                    //I don't think this actually matters, but I did it to be consistent with how you are supposed to place the ScriptManager when used declaritevly
                    this.Page.Form.Controls.AddAt(0, _AjaxManager);
                }
            }
        }

    }

}